<template>
    <div class="myYard"> 
        <el-card>
            <div class="top-main">
            <el-form class="top-form-fl" ref="tableRef" :inline="true"  label-width="auto" :model="yardSearchData" style="width: 100%;">
                <el-form-item label="港口" prop="yardPort">
                    <el-input v-model="yardSearchData.yardPort" clearable placeholder="请输入港口名"/>
                </el-form-item>
                <el-form-item label="堆场名称" prop="yardName">
                    <el-input v-model="yardSearchData.yardName" clearable  placeholder="请输入堆场名"/>
                </el-form-item>
                <el-form-item label="所在城市" prop="cityId">
                    <SelectCity :selectCityId="yardSearchData.cityId" :index="1" :config="{}" @cityId="selectCity"></SelectCity>
                </el-form-item>
            </el-form>
            <div class="top-from-fr">
                <el-button class="top-Search" @click="getTableList" type="primary">搜索</el-button>
                <el-button class="top-Refresh" @click="restData">重置</el-button>
            </div>   
        </div>
        </el-card>
        <el-card class="marginTop20" style="padding-bottom: 20px;">
            <el-row align="middle" gutter="10" class="marginBottom10 marginTop10">  <!-- 5-出租中 10-仓库中 15-待发布 -->
                <el-col :span="1" :class="{'cursor':true, 'select-style': isActive1}" @click="checkStatus('')">全部</el-col>
                <el-col :span="1" :class="{'cursor':true, 'select-style': isActive2}" @click="checkStatus(5)">已发布</el-col>
                <el-col :span="1" :class="{'cursor':true, 'select-style': isActive3}" @click="checkStatus(10)">已下架</el-col>
                <el-col :span="1" :class="{'cursor':true, 'select-style': isActive4}" @click="checkStatus(15)">待发布</el-col>
                <el-col :offset="12" :span="1.5">
                    <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有堆场" placement="left">
                        <template v-if="isSelectAll">
                            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
                        </template>
                        <template v-else>
                            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
                        </template>
                    </el-tooltip>
                </el-col>
                <el-col :span="1.5"><el-button type="danger" :icon="Delete" round size="small" @click="batchDelete">批量删除</el-button></el-col>
                <el-col :span="1.5"><el-button type="warning" :icon="Download" round size="small" @click="batchOffShelf">批量下架</el-button></el-col>
                <el-col :span="1.5"><el-button type="success" :icon="Upload" round size="small" @click="batchOnShelf">批量上架</el-button></el-col>
                <el-col :span="1.5"><el-button type="primary" :icon="Plus" round size="small" @click="handleAddYard">发布堆场</el-button></el-col>
            </el-row>
            <Table ref="tableRef1" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" style="width: 100%;" @pageChange="onTablePageChange" @activEdit="activEdit" 
            @activDelete="batchDelete" @activlist="batchOnShelf"  @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
            </Table>
        </el-card>
    </div>
</template>
<script lang="ts" setup>
import SelectCity from '@/components/citySelect/selectCity'
import Table from '@/components/table'
import { yardSelfPage , deleteYard, onShelf,offShelf } from '@/api/yardManage'
import { ref, reactive, onMounted} from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { Delete, Download, Upload, Plus, Finished } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter();
const tableRef = ref()
const statusVal = ref() //堆场发布状态
const yardSearchData = ref({
    yardPort: '',
    yardName:'',
    cityId:''
})
const param = reactive({
    pageNum:1,
    pageSize:10,
    total:0
})

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'yardPort', colWidth: '200', title: '港口', type: 'text', isCheck: true },
    { key: 'yardName', colWidth: '200', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'cityName', colWidth: '200', title: '所在城市', type: 'text', isCheck: true },
    { key: 'yardArea', colWidth: '200', title: '场地面积（M²）', type: 'text', isCheck: true },
    { key: 'storageCapacity', colWidth: '200', title: '场地容量(TEU)', type: 'text', isCheck: true },
    { key: 'throughputAbility', colWidth: '200', title: '吞吐能力(箱/月)', type: 'text', isCheck: true },
    { key: 'releaseDate', colWidth: '200', title: '发布日期', sortable:true, type: 'date', isCheck: true },
    {
      key: 'status', colWidth: '100', title: '发布状态', type: 'filter',
      filter: {5:'出租中',10:'仓库中',15:'待发布'}, //5-堆存中、10-提箱中、15-已提、20-未还、25-还箱中 30-已卖
      cFilter: { 5: '#2158F3', 10: '#efac10', 15: '#22A86D' }, isCheck: true
    },
    { key: 'releaseDate', colWidth: '200', title: '创建日期', sortable:true, type: 'date', isCheck: true },
    { key: 'releaseDate', colWidth: '200', title: '更新日期', sortable:true, type: 'date', isCheck: true },
    {
      key: 'operate',
      colWidth: '200',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          icon: 'Edit',
          command: 'activEdit',
          content: '编辑',
        },
        {
          icon: 'Delete',
          command: 'activDelete',
          content: '删除',
        },
        {  
          icon: 'Upload',
          command: 'activlist',
          content: '上架'
        },
      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
 
});
const getTableList = () => { 
    let reqParam= {
        pageNum: param.pageNum,
        pageSize: param.pageSize,
        yardPort: yardSearchData.value.yardPort,
        yardName: yardSearchData.value.yardName,
        cityId: yardSearchData.value.cityId,
        status: statusVal.value,
        sortBeans:[{"field":"yardPort","isAsc":"desc"}]
    }
    yardSelfPage(reqParam).then(res => { 
        console.log(res)
        table.data = res.data.list
        table.config.total = res.data.total;
    })
};

const restData = () => { 
    yardSearchData.value.yardPort = ''
    yardSearchData.value.yardName = ''
    yardSearchData.value.cityId = ''
    getTableList()
};

const isActive1 = ref(true)
const isActive2 = ref(false)
const isActive3 = ref(false)
const isActive4 = ref(false)
const checkStatus = (status: any) => {
    switch (status) {
        case '':
            isActive1.value = true
            isActive2.value = false
            isActive3.value = false
            isActive4.value = false
            statusVal.value = ''
            break;
        case 5:
            isActive1.value = false
            isActive2.value = true
            isActive3.value = false
            isActive4.value = false
            statusVal.value = '5'
            break;
        case 10:
            isActive1.value = false
            isActive2.value = false
            isActive3.value = true
            isActive4.value = false
            statusVal.value = '10'
            break;
        case 15:
            isActive1.value = false
            isActive2.value = false
            isActive3.value = false
            isActive4.value = true
            statusVal.value = '15'
            break;
    }
    // queryParameters.status = status
    getTableList()
}

// 发布堆场
const handleAddYard = () => { 
    router.push({
        path: '/yardServer/publishyard',
        query: {type: 'add'}
    })
};
// 编辑堆场
const activEdit = (row) => { 
    router.push({
        path: '/yardServer/publishyard',
        query: { type: 'edit',id:row.id }
    })
};

const tableRef1 = ref({ multipleSelection: []})
// 批量删除
const batchDelete = (row) => { // 需要删除的id （单个删除时使用）
    let checkAllItem = []
    if(row.id){
        checkAllItem.push(row)
    }else{
        if(isSelectAll.value){
            checkAllItem = tableRef1.value.multipleSelection
        }else{
            checkAllItem = allId.value
        } 
    }
   
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要删除的堆场！')
    ElMessageBox.confirm('确认删除选中的堆场？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteYard(ids).then((res: any) => {
            if(res.code == "00000"){
                ElMessage.success("删除成功！")
                getTableList()
            }
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
};
// 批量上架
const batchOnShelf = (row) => { 
    let checkAllItem = []
    if(row.id){
        checkAllItem.push(row)
    }else{
        if(isSelectAll.value){
            checkAllItem = tableRef1.value.multipleSelection
        }else{
            checkAllItem = allId.value
        } 
    }
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要上架的堆场！')
    ElMessageBox.confirm('确认上架选中的堆场？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        onShelf(ids).then((res: any) => {
            if(res.code == "00000"){
                ElMessage.success("上架成功！")
                getTableList()
            }
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
};

// 批量下架
const batchOffShelf = () => { 
    let checkAllItem = []
    if(isSelectAll.value){
        checkAllItem = tableRef1.value.multipleSelection
    }else{
        checkAllItem = allId.value
    } 
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要下架的堆场！')
    ElMessageBox.confirm('确认下架选中的堆场？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        offShelf(ids).then((res: any) => {
            if(res.code == "00000"){
                ElMessage.success("下架成功！")
                getTableList()
            }
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
};
onMounted(() => { 
    getTableList()
});
const selectCity = (cityInfo) =>{
    yardSearchData.value.cityId = cityInfo
}

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    await yardSelfPage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef1.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef1.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableList()
};
</script>
<style lang="scss" scoped>
.myYard{
    margin: 20px;
}
.cursor{
    cursor:pointer;
    text-align: center;
}

.select-style{
    color: #2158F3;
    border-bottom: 2px solid #2158F3;
}
</style>